package cn.skycity.auth.security.userdetails.user;

import cn.skycity.admin.api.UserFeignClient;
import cn.skycity.admin.pojo.entity.SysUser;
import cn.skycity.auth.security.userdetails.SysUserDetails;
import cn.skycity.common.model.Result;
import cn.skycity.common.model.ResultCode;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result<SysUser> result = userFeignClient.getUserByUsername(username);
        SysUserDetails userDetails = null;
        if (result.isSuccess()) {
            SysUser user = result.getResult();
            if (null != user) {
                user.setRoles(List.of("admin"));
                userDetails = new SysUserDetails(user);
            }
        }
        if (userDetails == null) {
            throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.getMsg());
        } else if (!userDetails.isEnabled()) {
            throw new DisabledException(ResultCode.USER_ACCOUNT_LOCKED.name());
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException(ResultCode.USER_ACCOUNT_LOCKED.getMsg());
        } else if (!userDetails.isAccountNonExpired()) {
            throw new AccountExpiredException(ResultCode.USER_ACCOUNT_INVALID.getMsg());
        }
        return userDetails;
    }

}
